package com.whjz.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import net.sf.json.JSONObject;

/**
 * HTTP通讯工具类
 *
 */
public class HttpUtil {
	static final String UTF8ENCODING = "utf-8";
	
	private static final CloseableHttpClient httpclient = HttpClients.createDefault();
	private static final String userAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36";

	/**
	 * <p>Title: sendGet</p>
	 * <p>Description: 发送HttpGet请求</p>
	 * @param url
	 * @return
	 */
	public static String sendGet(String url) {
		String result = null;
		CloseableHttpResponse response = null;
		try {
			HttpGet httpGet = new HttpGet(url);
			httpGet.setHeader("User-Agent", userAgent);
			response = httpclient.execute(httpGet);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				result = EntityUtils.toString(entity);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	/**
	 * <p>Title: sendPost</p>
	 * <p>Description: 发送HttpPost请求，参数为map</p>
	 * @param url
	 * @param map
	 * @return
	 */
	public static String sendPost(String url, Map<String, String> map) {
		// 设置参数
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		for (Map.Entry<String, String> entry : map.entrySet()) {
			formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
		}
		// 编码
		UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
		// 取得HttpPost对象
		HttpPost httpPost = new HttpPost(url);
		// 防止被当成攻击添加的
		httpPost.setHeader("User-Agent", userAgent);
		// 参数放入Entity
		httpPost.setEntity(formEntity);
		CloseableHttpResponse response = null;
		String result = null;
		try {
			// 执行post请求
			response = httpclient.execute(httpPost);
			// 得到entity
			HttpEntity entity = response.getEntity();
			// 得到字符串
			result = EntityUtils.toString(entity);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	/**
	 * <p>Title: sendPost</p>
	 * <p>Description: 发送HttpPost请求，参数为File</p>
	 * @param url
	 * @param file
	 * @return
	 */
	public static String sendPost(String url, File file) {
		String result = null;
		HttpPost httpPost = new HttpPost(url);
		// 防止被当成攻击添加的
		httpPost.setHeader("User-Agent", userAgent);
		MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
		multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
		multipartEntity.addPart("media", new FileBody(file));
		httpPost.setEntity(multipartEntity.build());
		CloseableHttpResponse response = null;
		try {
			response = httpclient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			result = EntityUtils.toString(entity);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭CloseableHttpResponse
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;

	}

	/**
	 * <p>Title: sendPost</p>
	 * <p>Description: 发送HttpPost请求，参数为JSON串</p>
	 * @param url
	 * @param jsonStr
	 * @return
	 */
	public static String sendPost(String url, String jsonStr) {
		String result = null;
		// 字符串编码
		StringEntity entity = new StringEntity(jsonStr, Consts.UTF_8);
		// 设置content-type
		entity.setContentType("application/json");
		HttpPost httpPost = new HttpPost(url);
		// 防止被当成攻击添加的
		httpPost.setHeader("User-Agent", userAgent);
		// 接收参数设置
		httpPost.setHeader("Accept", "application/json");
		httpPost.setEntity(entity);
		CloseableHttpResponse response = null;
		try {
			response = httpclient.execute(httpPost);
			HttpEntity httpEntity = response.getEntity();
			result = EntityUtils.toString(httpEntity);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭CloseableHttpResponse
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	/**
	 * <p>Title: sendPost</p>
	 * <p>Description: 发送HttpPost请求</p>
	 * @param url
	 * @return
	 */
	public static String sendPost(String url) {
		String result = null;
		// 得到一个HttpPost对象
		HttpPost httpPost = new HttpPost(url);
		// 防止被当成攻击添加的
		httpPost.setHeader("User-Agent", userAgent);
		CloseableHttpResponse response = null;
		try {
			// 执行HttpPost请求，并得到一个CloseableHttpResponse
			response = httpclient.execute(httpPost);
			// 从CloseableHttpResponse中拿到HttpEntity
			HttpEntity entity = response.getEntity();
			// 将HttpEntity转换为字符串
			result = EntityUtils.toString(entity);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭CloseableHttpResponse
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}
	public static String sendPosts(String url, String param) throws Exception {
		String code = null;
		String msg = null;
		PrintWriter out = null;
		BufferedReader in;
		in = null;
		String result = "";
		Map resultMap = null;
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			HttpURLConnection conn = (HttpURLConnection) realUrl
					.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*"	);
			conn.setRequestProperty("connnection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestMethod("POST");
			conn.setConnectTimeout(20*1000); // 毫秒  20秒超时
			conn.setReadTimeout(20*1000); // 毫秒 20秒超时
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"utf-8"));
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();

			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
//			LOG.info("sendPost result:" + result);
//			LOG.info("sendPost result JSON:" + JsonUtils.stringToMap(result));
			/*resultMap = new HashMap();
			if("JSON".equals(type.toUpperCase())){
				resultMap =	JsonUtils.stringToMap(result);
			}*/
		} catch (Exception e) {
			throw e;
		}finally { // 使用finally块来关闭输出流、输入流
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}
    /**
     * 创建spring web的HttpEntity
     * @param Object o
     * @return
     */
    public static org.springframework.http.HttpEntity<String> createHttpEntity(Object o) {
    	//创建设置header信息  
		HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        
        JSONObject jsonObj = JSONObject.fromObject(o);			//对象转jsonStr
        org.springframework.http.HttpEntity<String> entity = new org.springframework.http.HttpEntity<String>(jsonObj.toString(), headers);		//构建消息实体
        return entity;
    }
    
    
    public static void main(String[] args)  {
    	String url = "http://localhost:8901/login";
    	Map<String,String> map = new HashMap<String,String>();
    	map.put("userJson", "11");
    	sendPost(url, JSONObject.fromObject(map).toString());
	}
}
